package cn.huijielong.modules.pay.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.huijielong.common.annotation.NoAuthFilter;
import cn.huijielong.common.utils.Query;
import cn.huijielong.common.utils.RD;
import cn.huijielong.common.utils.VSUtil;
import cn.huijielong.common.wxpay.sdk.WXPayUtil;
import cn.huijielong.modules.group.service.OrderService;
import cn.huijielong.modules.pay.service.PaymentService;
import cn.huijielong.modules.pay.service.impl.WXPayService;
import cn.huijielong.modules.sys.controller.AbstractController;




/**
 * 支付
 */
@RestController
@RequestMapping("/pay")
public class PaymentController  extends AbstractController{
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private WXPayService wxPayService;
	
	/**
	 * 列表
	 */
	@RequestMapping("/unifiedOrder")
	public RD unifiedOrder(){
		Long buyUserId=getUserId();
		if(buyUserId==null || buyUserId.longValue()==0) {
			logger.error("用户ID为0，未登录，不能操作");
			return RD.error("未登录，不能操作");
		}
		net.sf.json.JSONObject json=VSUtil.requestToJSON();
        
        return paymentService.unifinedOrder(buyUserId, json);
	}
	
	
	/**
	 * 信息
	 */
	@NoAuthFilter
	@RequestMapping("/wx/notify")
	@ResponseBody
	public String notify_wx(){
		Query query=Query.createRequest();
		String orderNo = query.getString("out_trade_no");
		logger.info("微信支付异步通知，orderNo={}处理开始",orderNo);
		try {
			wxPayService.isSignatureValid(query);
			paymentService.trade(orderNo);
			logger.info("微信支付异步通知，orderNo={}处理结束",orderNo);
			return WXPayUtil.getNotifyMsg(true, "OK");
		}catch(Exception e) {
			logger.error("微信支付异步通知，orderNo={}处理失败",orderNo, e);
			return WXPayUtil.getNotifyMsg(false, e.getLocalizedMessage());
		}
	}
	
	
}
